package com.mustafaiev.tair.mweather.xml;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.mustafaiev.tair.mweather.forecast.Town;

/**
 * XML parser handler for towns.
 * 
 * Creation date: 2 Sep 2011 23:12:17
 * 
 * @author Tair Mustafaiev
 * 
 */
public class TownXMLHandler extends DefaultHandler {

	private ArrayList<Town> towns;
	private Town town;
	StringBuilder builder = null;
	TownXMLElement element;

	/**
	 * @return {@link ArrayList} of towns
	 */
	public ArrayList<Town> getTowns() {
		return this.towns;
	}

	@Override
	public void startDocument() throws SAXException {
		super.startDocument();
		this.towns = new ArrayList<Town>();
		this.town = new Town();
		this.builder = new StringBuilder();

	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		super.characters(ch, start, length);
		String value = new String(ch, start, length).trim();
		if (!value.equals("")) {
			switch (this.element) {
			case CITY:
				this.town.setTownName(value);
				break;
			case NEW_ID:
				this.town.setTownNewId(value);
				break;
			case OLD_ID:
				this.town.setTownOldId(value);
				break;
			}
		}
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		super.startElement(uri, localName, qName, attributes);

		if (!TownXMLElement.WEATHER.toString().equalsIgnoreCase(qName)
				|| !TownXMLElement.GISMETEO.toString().equalsIgnoreCase(qName)
				|| !TownXMLElement.ID.toString().equalsIgnoreCase(qName)) {
			this.element = TownXMLElement.valueOf(qName.toUpperCase());
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		super.endElement(uri, localName, qName);
		if (TownXMLElement.GISMETEO.toString().equalsIgnoreCase(qName)) {
			// add town to list
			this.towns.add(this.town);
			// reinitialize objects
			this.town = new Town();
		}
	}

}
